package org.dydl.controller.system;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.UUID;

//import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
 
 
/**
 * 文件上传类
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/file")
public class UploadController {
 
    private static final Logger LOG = Logger.getLogger(UploadController.class);      
 
    private static final HashMap<String, String> TypeMap = new HashMap<String, String>();

	private static final String BASE_PATH = "d://temp";
    //设置文件允许上传的类型
    static {
        TypeMap.put("image", "gif,jpg,jpeg,png,bmp");
        TypeMap.put("flash", "swf,flv");
        TypeMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        TypeMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf");
    }
     
    // 设置文件上传大小
    public static long fileSize = 3 * 1024 * 1024;
    /**
     * 文件上传
     *
     * @param file
     * @param request
     * @return message: -1 没有文件上传 0 上传成功 1 上传失败 2 文件超过上传大小 3 文件格式错误 4 上传文件路径非法 5 上传目录没有写权限
     *      
     *
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public void imageUpload(@RequestParam("file") MultipartFile file) {
        
    	LOG.info("file name is :" + file.getOriginalFilename());
        if (!file.isEmpty()) {
         
            //当文件超过设置的大小时，则不运行上传
            //if (file.getSize() > fileSize) {
            //    backInfo(response, false, 2, "");
            //    return;
            //}
            //获取文件名后缀
            String OriginalFilename = file.getOriginalFilename();
            String fileSuffix = OriginalFilename.substring(
                    OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
             
            //String fileSuffix="jpeg";
             
            //判断该类型的文件是否在允许上传的文件类型内
            //if (!Arrays.asList(TypeMap.get("file").split(",")).contains(
            //        fileSuffix)) {
            //    backInfo(response, false, 3, "");
            //    return;
            //}
            //if (!ServletFileUpload.isMultipartContent(request)) {
            //   backInfo(response, false, -1, "");
            //    return;
            //}
            // 检查上传文件的目录
//            File uploadDir = new File(BASE_PATH);
            //if (!uploadDir.isDirectory()) {
            //    if (!uploadDir.mkdir()) {
            //        backInfo(response, false, 4, "");
            ///        return;
            //    }
            //}
            // 是否有上传的权限
            //if (!uploadDir.canWrite()) {
            //    backInfo(response, false, 5, "");
            //    return;
            //}
             
            //新文件名
            String newname = "";
            //if(null != filePre){
            //    newname += filePre;//对应模块上传的文件名前缀
            //}
             newname += UUID.randomUUID().toString() + "." + fileSuffix;
 
            try {
 
                 //创建文件
                File saveFile = new File(BASE_PATH, newname);
                //保存文件
                file.transferTo(saveFile);
                //FileTranser.saveFielByFileName(file, uploadPath, newname);
                //backInfo(response, true, 0, newname);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
                //backInfo(response, false, 1, "");
                return;
            }
        } else {
            //backInfo(response, false, -1, "");
            return;
        }
 
    }
    
    /**
     * POST /uploadFile -> receive and locally save a file.
     * 
     * @param uploadfile The uploaded file as Multipart file parameter in the 
     * HTTP request. The RequestParam name must be the same of the attribute 
     * "name" in the input tag with type file.
     * 
     * @return An http OK status in case of success, an http 4xx status in case 
     * of errors.
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadFile(
        @RequestParam("uploadfile") MultipartFile uploadfile) {
      
    	JSONObject object = new JSONObject();
    	
      try {
        // Get the filename and build the local file path
        String filename = uploadfile.getOriginalFilename();
        String directory = "d:\\temp";
        String filepath = Paths.get(directory, filename).toString();
        
        // Save the file locally
        BufferedOutputStream stream =
            new BufferedOutputStream(new FileOutputStream(new File(filepath)));
        stream.write(uploadfile.getBytes());
        stream.close();
      }
      catch (Exception e) {
        System.out.println(e.getMessage());
        object.put("success", "false");
        //return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
      }
      object.put("success", "true");
      return object;
      //return new ResponseEntity<>(HttpStatus.OK);
    } // method uploadFile
    
}